package com.google.code.jcooky.rpc;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;

import com.google.code.jcooky.rpc.server.RPCServlet;

public class MockHttpServer {
	public static class MockTestServlet extends HttpServlet {
		public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
			PrintWriter writer = res.getWriter();
			
			String echo = req.getHeader("echo");
			
			writer.write(echo);
		}
	}
	private Server webServer;
	private WebAppContext webAppContext;
	
	public void start(String webContextPath, int port) throws IOException {
		webServer = new Server(port);
		webServer.setThreadPool(new QueuedThreadPool());
		
		webAppContext = new WebAppContext(webContextPath, "/");
		webAppContext.setDefaultsDescriptor(getClass().getResource("/webdefault.xml").getFile());
		webAppContext.setDescriptor(getClass().getResource("/web.xml").getFile());
		webAppContext.addServlet(MockTestServlet.class, "/mock");
		
		webServer.setHandler(webAppContext);
		
		try {
			webServer.start();
		} catch(Exception e) {
			throw new IOException("Error MockHttpServer", e);
		}
	}
	
	public void stop() throws Exception {
		webServer.stop();
		webServer.destroy();
	}
}
